package com.xbongbong.paas.connection.service.imp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.admin.domain.entity.RaidersEntity;
import com.xbongbong.admin.model.RaidersModel;
import com.xbongbong.admin.pojo.dto.MirrorInstallAllDTO;
import com.xbongbong.admin.pojo.dto.MirrorInstructionAllDTO;
import com.xbongbong.admin.pojo.vo.MirrorConfigListVo;
import com.xbongbong.admin.pojo.vo.MirrorInstallAllVO;
import com.xbongbong.admin.pojo.vo.MirrorInstructionAllVO;
import com.xbongbong.admin.pojo.vo.RaidersListVO;
import com.xbongbong.admin.pojo.vo.RaidersVO;
import com.xbongbong.paas.connection.enums.OpenAppEnum;
import com.xbongbong.paas.connection.enums.YuncodeActionEnum;
import com.xbongbong.paas.connection.pojo.cloudcode.dto.CloudCodeAddDTO;
import com.xbongbong.paas.connection.pojo.cloudcode.dto.CloudCodeDeleteDTO;
import com.xbongbong.paas.connection.pojo.cloudcode.dto.CloudCodeEnableDTO;
import com.xbongbong.paas.connection.pojo.cloudcode.dto.CloudCodeUpdateDTO;
import com.xbongbong.paas.connection.pojo.module.vo.IndustryVo;
import com.xbongbong.paas.connection.pojo.module.vo.OpenAppListVo;
import com.xbongbong.paas.connection.service.IOpenAppService;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.feign.ModuleCenterFeignClient;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.manager.feign.MirrorFeignClent;
import com.xbongbong.paas.model.CloudCodeControlModel;
import com.xbongbong.paas.model.CloudCodePermissionModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.dto.ApplicationAddDTO;
import com.xbongbong.paas.pojo.dto.UserInfoDTO;
import com.xbongbong.paas.pojo.vo.ApplicationAddVO;
import com.xbongbong.paas.pojo.vo.UserInfoVO;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DigestUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.appmodule.pojo.dto.AppModuleOpenDTO;
import com.xbongbong.pro.appmodule.pojo.vo.AppModuleOpenVO;
import com.xbongbong.pro.domain.entity.CloudCodeControlEntity;
import com.xbongbong.pro.domain.entity.CloudCodePermissionEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.cloudcode.enums.CloudCodeControlEnum;
import com.xbongbong.pro.enums.errorcodes.ApiErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.raiders.enums.RaidersGroupRecommendEnum;
import com.xbongbong.pro.enums.raiders.enums.RaidersPublishEnum;
import com.xbongbong.pro.menu.pojo.dto.MenuChangeStateDTO;
import com.xbongbong.pro.menu.pojo.vo.MenuChangeStateVO;
import com.xbongbong.pro.packageInfo.pojo.vo.BasePackageInfoVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.OpenAppEntity;
import com.xbongbong.saas.model.OpenAppModel;
import com.xbongbong.saas.service.AppModuleService;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * 云叩控件同步到pro
 * 创建时间 2020/9/23 4:27 PM
 * 修改时间 2020/9/23 4:27 PM
 *
 * @author chy
 */
@Component
public class CloudCodeService implements IOpenAppService {

    private static final Logger LOG = LoggerFactory.getLogger(CloudCodeService.class);

    @Resource
    private OpenAppModel openAppModel;
    @Resource
    private CloudCodeControlModel cloudCodeControlModel;
    @Resource
    private CloudCodePermissionModel cloudCodePermissionModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private UserService userService;
    @Resource
    private AppModuleService appModuleService;
    @Resource
    private ModuleCenterFeignClient moduleCenterFeignClient;
    @Resource
    private MirrorFeignClent mirrorFeignClent;
    @Resource
    private RaidersModel raidersModel;

    @Override
    public JSONObject getHeader() {
        return null;
    }

    @Override
    public void dataInit(String corpid) throws XbbException {
    }

    @Override
    public JSONObject dataInitSchedule() {
        return null;
    }

    @Override
    public BaseVO openAppApiCallbackAccept(JSONObject jsonObject) throws XbbException {
        BaseVO baseVO = new BaseVO();
        String action = jsonObject.getString("action");
        JSONArray array = jsonObject.getJSONArray("array");
        YuncodeActionEnum cloudCodeActionEnum = YuncodeActionEnum.getByAlias(action);

        if (Objects.nonNull(array)) {
            for (Object object : array) {
                JSONObject json = (JSONObject)object;
                switch (cloudCodeActionEnum) {
                    case ADD:
                        addAction(json);
                        break;
                    case UPDATE:
                        updateAction(json);
                        break;
                    case DELETE:
                        deleteAction(json);
                        break;
                    case ENABLE:
                        enableAction(json);
                        break;
                    default:
                        break;
                }
            }
        }

        if (Objects.equals(cloudCodeActionEnum, YuncodeActionEnum.MODULE_CENTER)) {
            baseVO = moduleCenterApiCallbackAccept(jsonObject);
        }

        return baseVO;
    }

    /**
     * 模板中心相关接口
     *
     * @param jsonObject 前端传过来的参数信息
     * @return BaseVO
     * @throws XbbException
     */
    private BaseVO moduleCenterApiCallbackAccept(JSONObject jsonObject) throws XbbException {
        LOG.info("========================moduleCenterApiCallbackAccept========================");
        BaseVO baseVO = new BaseVO();
        String subAction = jsonObject.getString("subAction");
        switch (subAction) {
            case "getCorpIndustry":
                baseVO = getCorpIndustry(jsonObject);
                break;
            case "getPackageInfo":
                baseVO = getPackageInfo(jsonObject);
                break;
            case "openApp":
                baseVO = openApp(jsonObject);
                break;
            case "changeState":
                LOG.info("========================switch case changeState========================");
                baseVO = changeState(jsonObject);
                break;
            case "getOpenAppList":
                baseVO = getOpenAppList(jsonObject);
                break;
            case "getMirrorInstructionAll":
                LOG.info("========================switch case getMirrorInstructionAll========================");
                baseVO = getMirrorInstructionAll(jsonObject);
                break;
            case "installMirrorAll":
                LOG.info("========================switch case installMirrorAll========================");
                baseVO = installMirrorAll(jsonObject);
                break;
            case "getMirrorConfigList":
                LOG.info("========================switch case getMirrorConfigList========================");
                baseVO = getMirrorConfigList(jsonObject);
                break;
            case "getRaidersList":
                baseVO = getRaidersList();
                break;
            case "addApp":
                LOG.info("========================switch case addApp========================");
                baseVO = addApp(jsonObject);
                break;
            default:
                break;
        }
        return baseVO;
    }

    /**
     * 获取公司的行业
     *
     * @param jsonObject
     * @return IndustryVo
     * @throws XbbException
     */
    private IndustryVo getCorpIndustry(JSONObject jsonObject) throws XbbException {
        String corpid = jsonObject.getString("corpid");
        if (StringUtil.isEmpty(corpid)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        } else {
            CompanyEntity companyEntity = companyModel.getByKey(corpid);
            if (Objects.isNull(companyEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100011);
            } else {
                IndustryVo industryVo = new IndustryVo();
                industryVo.setIndustry(companyEntity.getIndustry());
                return industryVo;
            }
        }
    }

    /**
     * 获取套餐信息
     *
     * @param jsonObject
     * @return BasePackageInfoVO
     * @throws XbbException
     */
    private BasePackageInfoVO getPackageInfo(JSONObject jsonObject) throws XbbException {
        String corpid = jsonObject.getString("corpid");
        if (StringUtil.isEmpty(corpid)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        } else {
            return packageHelp.getBasePackageInfoFromRedis(corpid);
        }
    }

    /**
     * 模板中心：应用的第一次开启（开通应用）
     *
     * @param jsonObject
     * @return BaseVO
     * @throws XbbException
     */
    private AppModuleOpenVO openApp(JSONObject jsonObject) throws XbbException {
        String userId = jsonObject.getString("userId");
        String corpid = jsonObject.getString("corpid");
        // 需要开通的应用的相关信息
        String alias = jsonObject.getString("alias");
        String name = jsonObject.getString("name");
        String icon = jsonObject.getString("icon");
        String bgColor = jsonObject.getString("bgColor");
        JSONArray mirrorIdArr = jsonObject.getJSONArray("mirrorId");
        String operate = jsonObject.getString("operate");
        String platform = jsonObject.getString("platform");
        UserVO userVO = getUserVO(userId, corpid);

        AppModuleOpenDTO openDTO = new AppModuleOpenDTO();
        openDTO.setUserId(userId);
        openDTO.setCorpid(corpid);
        openDTO.setPlatform(platform);
        openDTO.setAlias(alias);
        openDTO.setName(name);
        openDTO.setIcon(icon);
        openDTO.setBgColor(bgColor);
        openDTO.setMirrorIdArr(mirrorIdArr);
        openDTO.setOperate(operate);
        openDTO.setLoginUserName(userVO.getName());
        openDTO.setLoginUser(userVO);
        XbbResponse<AppModuleOpenVO> response = moduleCenterFeignClient.openApp(openDTO);
        if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
            throw new XbbException(response.getCode(), response.getMsg());
        }
        return response.getResult();
    }

    /**
     * 开启或者关闭已经开通的应用
     *
     * @param jsonObject
     * @return MenuChangeStateVO
     * @throws XbbException
     */
    private MenuChangeStateVO changeState(JSONObject jsonObject) throws XbbException {
        LOG.info("========================changeState========================");
        String userId = jsonObject.getString("userId");
        String corpid = jsonObject.getString("corpid");
        // 开启或者关闭应用需要的信息
        Long appId = jsonObject.getLong("appId");
        boolean enable = jsonObject.getBoolean("enable");
        // 枚举值见MenuChangeStateDTO.TargetEnum
        Integer target = jsonObject.getInteger("target");

        UserVO userVO = getUserVO(userId, corpid);

        MenuChangeStateDTO menuChangeStateDTO = jsonObject.toJavaObject(MenuChangeStateDTO.class);
        menuChangeStateDTO.setLoginUserName(userVO.getName());
        menuChangeStateDTO.setLoginUser(userVO);
        menuChangeStateDTO.setAppId(appId);
        menuChangeStateDTO.setEnable(enable);
        menuChangeStateDTO.setTarget(target);
        XbbResponse<MenuChangeStateVO> response = moduleCenterFeignClient.changeState(menuChangeStateDTO);
        if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
            throw new XbbException(response.getCode(), response.getMsg());
        }
        return response.getResult();
    }

    /**
     * 获取开通的应用
     *
     * @param jsonObject
     * @return OpenAppListVo
     * @throws XbbException
     */
    private OpenAppListVo getOpenAppList(JSONObject jsonObject) throws XbbException {
        String userId = jsonObject.getString("userId");
        String corpid = jsonObject.getString("corpid");
        if (StringUtil.isEmpty(corpid)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "corpid不可为空");
        }
        Map<String, PaasAppEntity> openAppList = appModuleService.getOpenApp(corpid, userId);
        OpenAppListVo openAppListVo = new OpenAppListVo();
        openAppListVo.setOpenAppList(openAppList);
        return openAppListVo;
    }

    /**
     * 镜像应用详情：判断镜像是否已经安装
     *
     * @param jsonObject
     * @return MirrorInstructionAllVO
     * @throws XbbException
     */
    private MirrorInstructionAllVO getMirrorInstructionAll(JSONObject jsonObject) throws XbbException {
        LOG.info("========================getMirrorInstructionAll========================");
        String userId = jsonObject.getString("userId");
        String corpid = jsonObject.getString("corpid");
        JSONArray mirrorIdArr = jsonObject.getJSONArray("mirrorIdArr");

        MirrorInstructionAllDTO mirrorInstructionAllDTO = new MirrorInstructionAllDTO();
        mirrorInstructionAllDTO.setPlatform(PlatFormEnum.WEB.getValue());
        mirrorInstructionAllDTO.setCorpid(corpid);
        mirrorInstructionAllDTO.setUserId(userId);
        mirrorInstructionAllDTO.setModule(true);
        mirrorInstructionAllDTO.setMirrorIdArr(mirrorIdArr);
        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        XbbResponse<MirrorInstructionAllVO> response = mirrorFeignClent.getMirrorInstructionAll(mirrorInstructionAllDTO, lang);
        if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
            throw new XbbException(response.getCode(), response.getMsg());
        }
        return response.getResult();
    }

    /**
     * 镜像应用安装
     *
     * @param jsonObject
     * @return MirrorInstallAllVO
     * @throws XbbException
     */
    private MirrorInstallAllVO installMirrorAll(JSONObject jsonObject) throws XbbException {
        LOG.info("========================installMirrorAll========================");
        String userId = jsonObject.getString("userId");
        String corpid = jsonObject.getString("corpid");
        JSONArray mirrorIdArr = jsonObject.getJSONArray("mirrorIdArr");

        MirrorInstallAllDTO mirrorInstallAllDTO = new MirrorInstallAllDTO();
        mirrorInstallAllDTO.setPlatform(PlatFormEnum.WEB.getValue());
        mirrorInstallAllDTO.setCorpid(corpid);
        mirrorInstallAllDTO.setUserId(userId);
        mirrorInstallAllDTO.setModule(true);
        mirrorInstallAllDTO.setMirrorIdArr(mirrorIdArr);
        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        UserVO userVO = userService.getUserVO(corpid, userId, true, true);
        mirrorInstallAllDTO.setLoginUser(userVO);
        mirrorInstallAllDTO.setLoginUserName(userVO.getName());
        XbbResponse<MirrorInstallAllVO> response = mirrorFeignClent.installAll(mirrorInstallAllDTO, lang);
        if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
            throw new XbbException(response.getCode(), response.getMsg());
        }
        return response.getResult();
    }

    /**
     * 获取镜像配置
     *
     * @return MirrorConfigListVo
     * @throws XbbException
     */
    private MirrorConfigListVo getMirrorConfigList(JSONObject jsonObject) throws XbbException {
        LOG.info("========================getMirrorConfigList========================");
        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        XbbResponse<MirrorConfigListVo> response = mirrorFeignClent.getMirrorConfigList(jsonObject.toJavaObject(BaseDTO.class), lang);
        if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
            throw new XbbException(response.getCode(), response.getMsg());
        }
        return response.getResult();
    }

    /**
     * 获取价值攻略
     *
     * @return RaidersListVO
     * @throws XbbException
     */
    public RaidersListVO getRaidersList() throws XbbException {
        Map<String, Object> raidersMap = new HashMap<>();
        raidersMap.put("del", DelEnum.NORMAL.getDel());
        raidersMap.put("publish", RaidersPublishEnum.PUBLISH.getCode());
        raidersMap.put("orderByStr", "sort desc");
        raidersMap.put("columns", "id, name");
        List<RaidersEntity> raidersList = raidersModel.findEntitys(raidersMap);
        // 去掉推荐攻略
        raidersList.removeIf(item-> Objects.equals(item.getGroupId(), RaidersGroupRecommendEnum.RECOMMEND.getId()));
        RaidersListVO raidersListVO = new RaidersListVO();
        List<RaidersVO> raidersVOList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for(RaidersEntity entity : raidersList){
            RaidersVO raidersVO = new RaidersVO();
            BeanUtil.copyProperties(entity, raidersVO);
            raidersVOList.add(raidersVO);
        }
        raidersListVO.setList(raidersVOList);
        return raidersListVO;
    }

    /**
     * 新增自定義應用
     * @param jsonObject
     * @return
     * @throws XbbException
     */
    public ApplicationAddVO addApp(JSONObject jsonObject) throws XbbException {
        LOG.info("========================addApp========================");
        ApplicationAddDTO applicationAddDTO = jsonObject.toJavaObject(ApplicationAddDTO.class);
        applicationAddDTO.setUserId("system");
        XbbResponse<ApplicationAddVO> response = moduleCenterFeignClient.addApp(applicationAddDTO);
        if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
            throw new XbbException(response.getCode(), response.getMsg());
        }
        return response.getResult();
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @param corpid
     * @return UserVO
     * @throws XbbException
     */
    private UserVO getUserVO(String userId, String corpid) throws XbbException {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setCorpid(corpid);
        userInfoDTO.setUserId(userId);
        userInfoDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
        userInfoDTO.setPaasPermissionsFlag(true);
        userInfoDTO.setUserDetailFlag(true);
        userInfoDTO.setCompanyInfoFlag(false);
        UserInfoVO userInfoResp = userService.getUserInfo(userInfoDTO);
        return userInfoResp.getUser();
    }

    /**
     * 控件添加
     *
     * @param jsonObject
     * @throws XbbException 创建时间 2020/9/22 2:52 PM
     *                      修改时间 2020/9/22 2:52 PM
     * @author chy
     */
    private void addAction(JSONObject jsonObject) throws XbbException {
        CloudCodeAddDTO cloudCodeAddDTO = jsonObject.toJavaObject(CloudCodeAddDTO.class);


        CloudCodeControlEntity cloudCodeControlEntity = addCloudCodeControl(cloudCodeAddDTO);
        Integer type = cloudCodeControlEntity.getType();
        CloudCodeControlEnum cloudCodeControlEnum = CloudCodeControlEnum.getByCode(type);

        switch (cloudCodeControlEnum) {
            case MENU:
                addMenu(cloudCodeControlEntity);
                break;
            case BUTTON_LIST:
            case BUTTON_DETAIL:
            case TAB:
                addCloudCodePermission(cloudCodeControlEntity);
                break;
            case CARD_LEFT:
                break;
            case CARD_RIGHT:
                break;
            default:
                break;
        }
    }

    /**
     * 新建控件
     *
     * @param cloudCodeAddDTO
     * @return
     */
    private CloudCodeControlEntity addCloudCodeControl(CloudCodeAddDTO cloudCodeAddDTO) throws XbbException {

        CloudCodeControlEntity dbCloudCodeControl = cloudCodeControlModel.getByCcId(cloudCodeAddDTO.getCcId(), cloudCodeAddDTO.getCorpid());
        if (Objects.nonNull(dbCloudCodeControl)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100021, "相同的ccId，不可重复新建");
        }

        CloudCodeControlEntity cloudCodeControlEntity = getCloudCodeControlEntity(cloudCodeAddDTO);
        cloudCodeControlModel.insert(cloudCodeControlEntity);
        return cloudCodeControlEntity;
    }

    private void addCloudCodePermission(CloudCodeControlEntity cloudCodeControlEntity) {
        Long now = DateTimeUtil.getInt();
        CloudCodePermissionEntity cloudCodePermissionEntity = new CloudCodePermissionEntity();
        cloudCodePermissionEntity.setCorpid(cloudCodeControlEntity.getCorpid());
        cloudCodePermissionEntity.setSaasMark(cloudCodeControlEntity.getSaasMark());
        cloudCodePermissionEntity.setAppId(cloudCodeControlEntity.getAppId());
        cloudCodePermissionEntity.setFormId(cloudCodeControlEntity.getFormId());
        cloudCodePermissionEntity.setBusinessType(cloudCodeControlEntity.getBusinessType());
        cloudCodePermissionEntity.setEnable(cloudCodeControlEntity.getEnable());
        cloudCodePermissionEntity.setType(cloudCodeControlEntity.getType());
        String alias = getCloudCodeAlias(cloudCodeControlEntity.getId());
        cloudCodePermissionEntity.setAlias(alias);
        cloudCodePermissionEntity.setName(cloudCodeControlEntity.getName());
        cloudCodePermissionEntity.setFullName(cloudCodeControlEntity.getName());
        Integer type = cloudCodeControlEntity.getType();
        Integer isMenu = Objects.equals(CloudCodeControlEnum.MENU.getCode(), type) ? 1 : 0;
        cloudCodePermissionEntity.setIsMenu(isMenu);
        cloudCodePermissionEntity.setAddTime(now);
        cloudCodePermissionEntity.setUpdateTime(now);
        cloudCodePermissionEntity.setDel(BasicConstant.ZERO);
        cloudCodePermissionModel.insert(cloudCodePermissionEntity);
    }

    /**
     * 拼接云叩相关alias
     *
     * @param cloudCodeControlId
     * @return
     */
    private String getCloudCodeAlias(Long cloudCodeControlId) {
        return PaasConstant.CLOUD_CODE_ALIAS + "_" + cloudCodeControlId;
    }

    /**
     * 按钮添加
     *
     * @param cloudCodeControlEntity
     * @throws XbbException
     */
    private void addMenu(CloudCodeControlEntity cloudCodeControlEntity) throws XbbException {
        String corpid = cloudCodeControlEntity.getCorpid();
        Long appId = cloudCodeControlEntity.getAppId();
        String name = cloudCodeControlEntity.getName();
        String alias = getCloudCodeAlias(cloudCodeControlEntity.getId());
        int sort = 0;
        String url = "";
        String mobileUrl = "";
        if (Objects.equals(cloudCodeControlEntity.getPlatform(), PlatFormEnum.WEB.getValue())) {
            url = "1";
        } else if (Objects.equals(cloudCodeControlEntity.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            mobileUrl = "1";
        } else if (Objects.equals(cloudCodeControlEntity.getPlatform(), PlatFormEnum.ALL.getValue())) {
            url = "1";
            mobileUrl = "1";
        }
        Integer enable = cloudCodeControlEntity.getEnable();
        String color = "";
        String icon = "";
        String creatorId = "sys";
        PaasMenuEntity paasMenu = new PaasMenuEntity(corpid, appId, name, alias, sort, url, mobileUrl, enable,
                color, icon, creatorId);
        paasMenu.setSaasMark(SaasMarkEnum.PAAS.getCode());
        paasMenuModel.insert(paasMenu);
        addCloudCodePermission(cloudCodeControlEntity);
    }

    private CloudCodeControlEntity getCloudCodeControlEntity(CloudCodeAddDTO cloudCodeAddDTO) {
        Long now = DateTimeUtil.getInt();
        CloudCodeControlEntity cloudCodeControlEntity = new CloudCodeControlEntity();
        cloudCodeControlEntity.setCorpid(cloudCodeAddDTO.getCorpid());
        cloudCodeControlEntity.setSaasMark(cloudCodeAddDTO.getSaasMark());
        cloudCodeControlEntity.setAppId(cloudCodeAddDTO.getAppId());
        cloudCodeControlEntity.setFormId(cloudCodeAddDTO.getFormId());
        cloudCodeControlEntity.setBusinessType(cloudCodeAddDTO.getBusinessType());
        cloudCodeControlEntity.setType(cloudCodeAddDTO.getType());
        cloudCodeControlEntity.setPlatform(cloudCodeAddDTO.getPlatform());
        cloudCodeControlEntity.setCcId(cloudCodeAddDTO.getCcId());
        cloudCodeControlEntity.setEnable(cloudCodeAddDTO.getEnable());
        cloudCodeControlEntity.setName(cloudCodeAddDTO.getName());
        cloudCodeControlEntity.setActions(cloudCodeAddDTO.getActions());
        cloudCodeControlEntity.setAddTime(now);
        cloudCodeControlEntity.setUpdateTime(now);
        cloudCodeControlEntity.setDel(BasicConstant.ZERO);
        return cloudCodeControlEntity;
    }

    /**
     * 控件编辑
     *
     * @param jsonObject 创建时间 2020/9/22 2:53 PM
     *                   修改时间 2020/9/22 2:53 PM
     * @author chy
     */
    private void updateAction(JSONObject jsonObject) throws XbbException {
        CloudCodeUpdateDTO cloudCodeUpdateDTO = jsonObject.toJavaObject(CloudCodeUpdateDTO.class);
        CloudCodeControlEntity cloudCodeControlEntity = updateCloudCodeControl(cloudCodeUpdateDTO);
        Integer type = cloudCodeControlEntity.getType();
        CloudCodeControlEnum cloudCodeControlEnum = CloudCodeControlEnum.getByCode(type);

        switch (cloudCodeControlEnum) {
            case MENU:
                updateMenu(cloudCodeControlEntity);
                break;
            case BUTTON_LIST:
            case BUTTON_DETAIL:
            case TAB:
                updateCloudCodePermission(cloudCodeControlEntity);
                break;
            case CARD_LEFT:
                break;
            case CARD_RIGHT:
                break;
            default:
                break;
        }

    }

    private CloudCodeControlEntity updateCloudCodeControl(CloudCodeUpdateDTO cloudCodeUpdateDTO) throws XbbException {
        CloudCodeControlEntity cloudCodeControl = cloudCodeControlModel.getByCcId(cloudCodeUpdateDTO.getCcId(), cloudCodeUpdateDTO.getCorpid());
        if (Objects.isNull(cloudCodeControl)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "控件数据不存在");
        }
        cloudCodeControl.setName(cloudCodeUpdateDTO.getName());
        cloudCodeControl.setActions(cloudCodeUpdateDTO.getActions());
        cloudCodeControl.setUpdateTime(DateTimeUtil.getInt());
        cloudCodeControlModel.update(cloudCodeControl);
        return cloudCodeControl;
    }


    /**
     * 由于控件修改，菜单做相关变动
     *
     * @param cloudCodeControlEntity
     * @throws XbbException
     */
    private void updateMenu(CloudCodeControlEntity cloudCodeControlEntity) throws XbbException {
        String corpid = cloudCodeControlEntity.getCorpid();
        Long cloudCodeControlId = cloudCodeControlEntity.getId();
        PaasMenuEntity paasMenu = paasMenuModel.getByAlias(getCloudCodeAlias(cloudCodeControlId), corpid);
        if (Objects.isNull(paasMenu)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "菜单不存在");
        }
        paasMenu.setName(cloudCodeControlEntity.getName());
        paasMenuModel.update(paasMenu);
        updateCloudCodePermission(cloudCodeControlEntity);
    }

    private void updateCloudCodePermission(CloudCodeControlEntity cloudCodeControlEntity) throws XbbException {
        CloudCodePermissionEntity cloudCodePermission = cloudCodePermissionModel.getByAlias(getCloudCodeAlias(cloudCodeControlEntity.getId()),
                cloudCodeControlEntity.getCorpid());
        if (Objects.isNull(cloudCodePermission)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩权限不存在");
        }
        String name = cloudCodeControlEntity.getName();
        cloudCodePermission.setName(name);
        cloudCodePermission.setFullName(name);
        cloudCodePermissionModel.update(cloudCodePermission);
    }

    /**
     * 删除动作
     *
     * @param jsonObject
     * @throws XbbException 创建时间 2020/9/23 3:16 PM
     *                      修改时间 2020/9/23 3:16 PM
     * @author chy
     */
    private void deleteAction(JSONObject jsonObject) throws XbbException {
        CloudCodeDeleteDTO cloudCodeDeleteDTO = jsonObject.toJavaObject(CloudCodeDeleteDTO.class);
        Long ccId = cloudCodeDeleteDTO.getCcId();
        String corpid = cloudCodeDeleteDTO.getCorpid();
        CloudCodeControlEntity cloudCodeControl = cloudCodeControlModel.getByCcId(ccId, corpid);
        if (Objects.isNull(cloudCodeControl)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩控件不存在");
        }
        Long cloudCodeControlId = cloudCodeControl.getId();
        Integer type = cloudCodeControl.getType();
        CloudCodeControlEnum cloudCodeControlEnum = CloudCodeControlEnum.getByCode(type);
        switch (cloudCodeControlEnum) {
            case MENU:
                deleteMenu(corpid, cloudCodeControlId);
                break;
            case BUTTON_LIST:
            case BUTTON_DETAIL:
            case TAB:
                deleteCloudCodePermission(corpid, cloudCodeControlId);
                break;
            case CARD_LEFT:
                break;
            case CARD_RIGHT:
                break;
            default:
                break;
        }
        cloudCodeControlModel.deleteByCcId(corpid, ccId);
    }

    /**
     * 删除cloudCodeControlId对应的控件菜单及相关权限
     *
     * @param corpid
     * @param cloudCodeControlId
     * 创建时间 2020/9/23 2:55 PM
     * 修改时间 2020/9/23 2:55 PM
     * @author chy
     */
    private void deleteMenu(String corpid, Long cloudCodeControlId) throws XbbException {
        String alias = getCloudCodeAlias(cloudCodeControlId);
        PaasMenuEntity paasMenu = paasMenuModel.getByAlias(alias, corpid);
        if (Objects.isNull(paasMenu)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩菜单不存在");
        }
        paasMenuModel.delete(paasMenu.getId(), corpid);
        deleteCloudCodePermission(corpid, cloudCodeControlId);
    }

    /**
     * 删除cloudCodeControlId对应的权限
     *
     * @param corpid
     * @param cloudCodeControlId
     * 创建时间 2020/9/23 2:56 PM
     * 修改时间 2020/9/23 2:56 PM
     * @author chy
     */
    private void deleteCloudCodePermission(String corpid, Long cloudCodeControlId) {
        String alias = getCloudCodeAlias(cloudCodeControlId);
        cloudCodePermissionModel.deleteByAlias(corpid, alias);
    }

    /**
     * 控件启用/关闭操作
     *
     * @param jsonObject
     * @throws XbbException 创建时间 2020/9/23 3:22 PM
     *                      修改时间 2020/9/23 3:22 PM
     * @author chy
     */
    private void enableAction(JSONObject jsonObject) throws XbbException {
        CloudCodeEnableDTO cloudCodeEnableDTO = jsonObject.toJavaObject(CloudCodeEnableDTO.class);
        Long ccId = cloudCodeEnableDTO.getCcId();
        String corpid = cloudCodeEnableDTO.getCorpid();
        Integer enable = cloudCodeEnableDTO.getEnable();
        CloudCodeControlEntity cloudCodeControl = cloudCodeControlModel.getByCcId(ccId, corpid);
        if (Objects.isNull(cloudCodeControl)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩控件不存在");
        }
        Integer type = cloudCodeControl.getType();
        Long cloudCodeControlId = cloudCodeControl.getId();
        CloudCodeControlEnum cloudCodeControlEnum = CloudCodeControlEnum.getByCode(type);
        switch (cloudCodeControlEnum) {
            case MENU:
                enableMenu(corpid, cloudCodeControlId, enable);
                break;
            case BUTTON_LIST:
            case BUTTON_DETAIL:
            case TAB:
                enableCloudCodePermission(corpid, cloudCodeControlId, enable);
                break;
            case CARD_LEFT:
                break;
            case CARD_RIGHT:
                break;
            default:
                break;
        }
        enableCloudCodeControl(corpid, ccId, enable);
    }

    private void enableCloudCodeControl(String corpid, Long ccId, Integer enable) throws XbbException {
        CloudCodeControlEntity cloudCodeControl = cloudCodeControlModel.getByCcId(ccId, corpid);
        if (Objects.isNull(cloudCodeControl)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩控件不存在");
        }
        cloudCodeControl.setEnable(enable);
        cloudCodeControl.setUpdateTime(DateTimeUtil.getInt());
        cloudCodeControlModel.update(cloudCodeControl);
    }

    private void enableMenu(String corpid, Long cloudCodeControlId, Integer enable) throws XbbException {
        PaasMenuEntity paasMenu = paasMenuModel.getByAlias(getCloudCodeAlias(cloudCodeControlId), corpid);
        if (Objects.isNull(paasMenu)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩菜单不存在");
        }
        paasMenu.setEnable(enable);
        paasMenu.setUpdateTime(DateTimeUtil.getInt());
        paasMenuModel.update(paasMenu);
        enableCloudCodePermission(corpid, cloudCodeControlId, enable);
    }

    private void enableCloudCodePermission(String corpid, Long cloudCodeControlId, Integer enable) throws XbbException {
        CloudCodePermissionEntity cloudCodePermission = cloudCodePermissionModel.getByAlias(getCloudCodeAlias(cloudCodeControlId), corpid);
        if (Objects.isNull(cloudCodePermission)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "云叩权限不存在");
        }
        cloudCodePermission.setEnable(enable);
        cloudCodePermission.setUpdateTime(DateTimeUtil.getInt());
        cloudCodePermissionModel.update(cloudCodePermission);
    }

    @Override
    public void requestCheck(HttpServletRequest httpRequest, JSONObject data) throws XbbException {

        Integer openAppId = StringUtil.toInt(httpRequest.getHeader("openAppId"), null);
        Integer sysOpenAppId = OpenAppEnum.CLOUD_CODE.getOpenAppId();
        if (!Objects.equals(openAppId, sysOpenAppId)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, "openAppId错误");
        }
        if (data == null) {
            // 错误返回
            throw new XbbException(ApiErrorCodeEnum.API_ERROR_700005);
        }

        // 请求签名
        String sign = httpRequest.getHeader("sign");

        OpenAppEntity openApp = openAppModel.getByOpenAppId(openAppId);
        String token = openApp.getOpenAppToken();

        String calculateSign = DigestUtil.Encrypt(data.toJSONString() + token, "SHA-256");

        if (StringUtil.isEmpty(sign) || !sign.equalsIgnoreCase(calculateSign)) {
            throw new XbbException(ApiErrorCodeEnum.API_ERROR_700003, "签名验证失败");
        }
    }
}
